package com.mall.order.biz.handler;

import com.mall.commons.ShoppingCarts;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

/**
 * ciggar
 * create-date: 2019/8/1-下午5:05
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired
    RedissonClient redissonClient;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    // todo lsy
    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        RMap<Long, List<ShoppingCarts>> cartMap = redissonClient.getMap("shoppingCart");
        Long userId = createOrderContext.getUserId();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        List<ShoppingCarts> shoppingCartList = null;
        try {
            shoppingCartList = cartMap.get(userId);
        } catch (Exception ignored) {
        }

        // list中删除掉下单的购物车数据
        if (shoppingCartList != null && shoppingCartList.size() != 0) {
            shoppingCartList.removeIf(shoppingCarts -> buyProductIds.contains(shoppingCarts.getProductId()));

            // 将删除了下单的购物车缓存数据删除后重新存储到redis
            cartMap.put(userId, shoppingCartList);
        }

        return true;
    }
}
